<template>
	<view class="content">
		<view class="padding"  v-if="showUploadIcon">
			<lsj-upload ref="lsjUpload0" childId="upload1" :width="width" :height="height" :option="option" :size="size"
				:count="count" :formats="formats" :debug="debug" :instantly="instantly" @change="onChange"
				@uploadEnd="onuploadEnd">
				<view class="btn" :style="{width: width,height: height}">+</view>
			</lsj-upload>
		</view>

		<!-- 上传的文件展示 -->
		<view v-if="list.length>0">
			<view v-for=" v,i in list" :key="v" class="files">
				<view class="filesleft" @click="openfile(v)">
					{{v}}
				</view>
				<view class="filesright" @click="clear(v)" v-if="showsDelete">
					删除
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import BASE_URL from '@/api/env.js'
	// import pdf from 'vue-pdf';
	export default {
		data() {
			return {
				// 上传接口参数
				option: {
					// 上传服务器地址，此地址需要替换为你的接口地址
					url: BASE_URL + '/common/upload',
					// 上传附件的key
					name: 'file',
					// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
					header: {
						// 示例参数可删除
						'Authorization': 'Bearer ' + uni.getStorageSync('SET_TOKEN'),
					},
				},
				// 选择文件后是否立即自动上传，true=选择后立即上传
				instantly: true,
				// 必传宽高且宽高应与slot宽高保持一致
				width: '100rpx',
				height: '100rpx',
				// 限制允许上传的格式，空串=不限制，默认为空
				// formats: 'png,jpg,svg,pdf,doc,docx,PNG,JPG,SVG,PDF,DOC,DOCX',
				// formats: '',	
				// 文件上传大小限制
				size: 30,
				// 文件数量限制
				count: 99,
				// 文件回显列表
				files: new Map(),
				// 是否打印日志
				debug: false,
				list: []
			}
		},
		/* components: {
		    pdf
		}, */
		props: {
			// 回显的文件
			value: {
				type: Array,
				default: () => [],
			},
			/* value: {
				type: Map,
				default: () => new Map(),
			}, */
			// 上传的文件类型
			formats: {
				type: String,
				default: 'png,jpg,svg,pdf,doc,docx,PNG,JPG,SVG,PDF,DOC,DOCX,txt',
			},
			// 显示删除
			showsDelete: {
				type: Boolean,
				default: true,
			},
			// 显示上传图标
			showUploadIcon: {
				type: Boolean,
				default: true,
			}
		},
		watch: {
			value: {
				handler(v) {
					console.log(v, 'this.list----------')
					if (v && v.length) {
						v.forEach(item => {
							this.files.set(item.originalFilename || item.drawingName, {
								responseText: {
									...item,
									fileName: item.path || item.filePath,
									fileId: item.id || item.fileId,
								}
							})
						})
						this.list = [...this.files.keys()]
						// 强制更新视图
						this.$forceUpdate();
						this.$emit('input', this.files)
					}
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			// 打开文件
			openfile(v) {
				uni.showLoading({
					title: '加载中'
				});
				let data = this.files.get(v).responseText.fileName
				if (!data) {
					data = JSON.parse(this.files.get(v).responseText).fileName
				}
				/* if(!BASE_URL.includes('factory-api')){
					BASE_URL = `${BASE_URL}/factory-api`
				} */
				let url = BASE_URL + data
				const encodedURL = url.replace(/#/g, '%23');
				if (v.slice(-3) === 'pdf' || v.slice(-3) === 'doc' || v.slice(-4) === 'docx') {
					// 1. 先下载文件
					uni.downloadFile({
						url: encodedURL,
						success: (res) => {
							uni.hideLoading();
							const filePath = res.tempFilePath;
							// 2. 用原生API打开文档
							uni.openDocument({
								filePath: filePath,
								showMenu: true, // 显示右上角菜单，可以分享、转发等
								success: function() {
									console.log('打开文档成功');
								},
								fail: (err) => {
									console.error('打开文档失败', err);
									uni.showToast({
										title: '文件打开失败',
										icon: 'none'
									});
								}
							});
						},
						fail: (err) => {
							uni.hideLoading();
							console.error('下载文件失败', err);
							uni.showToast({
								title: '文件加载失败',
								icon: 'none'
							});
						}
					});
					/* uni.navigateTo({
						url: '/pagesIndex/pdf/filePreview?params=' + encodedURL
					}) */
				} else {
					uni.hideLoading();
					uni.previewImage({
						urls: [encodedURL],
						current: 0 // 当前显示图片的索引
					})
					/* uni.downloadFile({
						url: encodedURL,
						success: function(res) {
							var filePath = res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								showMenu: true,
								success: function(res) {
									uni.hideLoading();
								},
								fail: function() {
									uni.hideLoading();
								}
							});
						},
						fail: function() {
							uni.hideLoading();
						}
					}); */
				}
			},
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				// 更新当前状态变化的文件
				this.files.set(item.name, item);
				// 演示上传完成后取服务端数据
				if (item['responseText']) {
					this.files.get(item.name).responseText = JSON.parse(item.responseText);
				}
				this.list = [...this.files.keys()]
				// 强制更新视图
				this.$forceUpdate();
				this.$emit('input', this.files)
			},
			// 文件选择回调
			onChange(files) {
				// 更新选择的文件 
				this.files = files;
				// 强制更新视图
				this.$forceUpdate();
				// 演示重新定位组件
				this.$nextTick(() => {
					this.$refs.lsjUpload0.show();
				});
			},
			// 移除某个文件
			clear(name) {
				// name=指定文件名，不传name默认移除所有文件
				this.$refs['lsjUpload0'].clear(name);

				this.$emit('deleteFiles', name)

				this.list = this.list.filter(item => {
					return item !== name
				})
			},
			open() {
				uni.navigateTo({
					url: '/pages/nvue-demo/nvue-demo'
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.files {
		margin-top: 10rpx;

		@include center();

		.filesleft {
			@include white-space1(580rpx);
			color: #18A7F0;
		}

		.filesright {
			margin-left: 15rpx;
			color: red;
			padding: 10rpx;
		}
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 130rpx;
		line-height: 130rpx;
		text-align: center;
		font-size: 32rpx;
		background-color: #3F536E;
		color: #fff;
		z-index: 9999;
	}

	.content {
		/* padding-top: 130rpx; */
	}

	.flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.inputs {
		height: 100rpx;
		border-bottom: 1rpx solid #808080;
	}

	.padding {
		padding-top: 30rpx;
		/* padding-left: 30rpx;
		padding-bottom: 50rpx; */
	}

	.tab {
		display: flex;
		padding: 30rpx;
	}

	.tab view {
		height: 100rpx;
		line-height: 100rpx;
		flex: 1;
		text-align: center;
		border: 1rpx solid #2C405A;
	}

	.btn {
		height: 80rpx;
		background-color: #D9D9D9;
		color: #fff;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}

	.ts {
		line-height: 2em;
	}

	.nbtn {
		margin: 100rpx 50rpx;
	}
</style>